<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { AiLlmBrandApi } from '#/api/ai/llm/brand';
import type { AiLlmApi } from '#/api/ai/llm/llmModel';

import { computed, ref } from 'vue';

import { confirm, Page, useVbenModal } from '@vben/common-ui';
import { downloadFileFromBlobPart } from '@vben/utils';

import { Card, message, Tag } from 'ant-design-vue';

import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import { clearCache } from '#/api/ai/llm/brand';
import {
  deleteLlm,
  deleteLlmList,
  exportLlm,
  getLlmModelPage,
} from '#/api/ai/llm/llmModel';
import { Image } from '#/components/image';
import { $t } from '#/locales';

import { useGridColumns, useGridFormSchema } from './data';
import BrandList from './modules/brand-list.vue';
import Detail from './modules/detail.vue';
import Form from './modules/form.vue';
import QuickForm from './modules/quickForm.vue';

const selectedBrand = ref('');
const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});
const [QuickAddModal, quickAddModalApi] = useVbenModal({
  connectedComponent: QuickForm,
  destroyOnClose: true,
});
const [DetailModal, detailModalApi] = useVbenModal({
  connectedComponent: Detail,
  destroyOnClose: true,
});

/** 刷新表格 */
function handleRefresh() {
  gridApi.reload();
}

/** 创建AI模型管理 */
function handleCreate() {
  formModalApi.setData({}).open();
}
/** 一键添加 */
function handleQuickAdd() {
  quickAddModalApi.setData({}).open();
}
/** 编辑AI模型管理 */
function handleEdit(row: AiLlmApi.AiLlm) {
  formModalApi.setData(row).open();
}

/** 查看AI模型管理 */
function handleDetail(row: AiLlmApi.AiLlm) {
  detailModalApi.setData(row).open();
}

/** 删除AI模型管理 */
async function handleDelete(row: AiLlmApi.AiLlm) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.title || row.id]),
    duration: 0,
  });
  try {
    await deleteLlm(row.id as number);
    message.success({
      content: $t('ui.actionMessage.deleteSuccess', [row.title || row.id]),
    });
    handleRefresh();
  } finally {
    hideLoading();
  }
}

/** 批量删除AI模型管理 */
async function handleDeleteBatch() {
  await confirm($t('ui.actionMessage.deleteBatchConfirm'));
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deletingBatch'),
    duration: 0,
  });
  try {
    await deleteLlmList(checkedIds.value);
    checkedIds.value = [];
    message.success({
      content: $t('ui.actionMessage.deleteSuccess'),
    });
    handleRefresh();
  } finally {
    hideLoading();
  }
}

const checkedIds = ref<number[]>([]);
function handleRowCheckboxChange({ records }: { records: AiLlmApi.AiLlm[] }) {
  checkedIds.value = records.map((item) => item.id!);
}
// 左侧角色列标配计算屏幕高度
const heightLeft = computed(() => {
  return window.innerHeight - 180;
});
function handleBrandSelect(brand: AiLlmBrandApi.Brand) {
  selectedBrand.value = brand.key;
  gridApi.reload();
}
/** 导出表格 */
async function handleExport() {
  const data = await exportLlm(await gridApi.formApi.getValues());
  downloadFileFromBlobPart({ fileName: 'AI模型管理.xls', source: data });
}
/** 清除缓存 */
async function handleClearCache() {
  await confirm('确认清除缓存吗？');
  const hideLoading = message.loading({
    content: '清除缓存中...',
    duration: 0,
  });
  try {
    await clearCache();
    message.success({
      content: '清除缓存成功',
    });
    handleRefresh();
  } finally {
    hideLoading();
  }
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useGridFormSchema(),
  },
  gridOptions: {
    id: 'Llm-grid',
    columns: useGridColumns(),
    height: 'auto',
    pagerConfig: {
      enabled: true,
    },
    keepSource: true,
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getLlmModelPage(
            {
              pageNo: page.currentPage,
              pageSize: page.pageSize,
              ...formValues,
              brand: selectedBrand.value,
            },
            false,
            false,
          );
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    toolbarConfig: {
      refresh: true,
      search: true,
    },
  } as VxeTableGridOptions<AiLlmApi.AiLlm>,
  gridEvents: {
    checkboxAll: handleRowCheckboxChange,
    checkboxChange: handleRowCheckboxChange,
  },
});
</script>

<template>
  <Page auto-content-height>
    <FormModal @success="handleRefresh" />
    <DetailModal @success="handleRefresh" />
    <QuickAddModal @success="handleRefresh" />
    <div class="flex h-full w-full">
      <!-- 左侧部门树 -->
      <Card class="mr-4 h-full w-1/6">
        <div :style="{ height: `${heightLeft}px` }" style="overflow: auto">
          <BrandList @select="handleBrandSelect" />
        </div>
      </Card>
      <Grid table-title="AI模型列表" class="mr-4 h-full w-5/6">
        <template #toolbar-tools>
          <TableAction
            :actions="[
              {
                label: $t('ui.actionTitle.create', ['AI模型管理']),
                type: 'primary',
                icon: ACTION_ICON.ADD,
                auth: ['ai:aiLlm:save'],
                onClick: handleCreate,
              },
              {
                label: '一键添加',
                type: 'primary',
                icon: ACTION_ICON.ADD,
                auth: ['ai:aiLlm:save'],
                onClick: handleQuickAdd,
              },
              {
                label: '清楚缓存',
                type: 'primary',
                icon: ACTION_ICON.UNLOCK,
                auth: ['ai:LlmBrand:clearCache'],
                onClick: handleClearCache,
              },
            ]"
          />
        </template>
        <template #supportFeatures="{ row }">
          <Tag v-for="(item, index) in row.supportFeatures" :key="index">
            {{ item }}
          </Tag>
        </template>
        <template #icon="{ row }">
          <Image :src="row.icon" />
        </template>
        <template #actions="{ row }">
          <TableAction
            :actions="[
              {
                label: '查看',
                type: 'link',
                icon: ACTION_ICON.VIEW,
                auth: ['ai:aiLlm:query'],
                onClick: handleDetail.bind(null, row),
              },
              {
                label: $t('common.edit'),
                type: 'link',
                icon: ACTION_ICON.EDIT,
                auth: ['ai:aiLlm:update'],
                onClick: handleEdit.bind(null, row),
              },
              {
                label: $t('common.delete'),
                type: 'link',
                danger: true,
                icon: ACTION_ICON.DELETE,
                auth: ['ai:aiLlm:delete'],
                popConfirm: {
                  title: $t('ui.actionMessage.deleteConfirm', [row.id]),
                  confirm: handleDelete.bind(null, row),
                },
              },
            ]"
          />
        </template>
      </Grid>
    </div>
  </Page>
</template>
